package com.benshou.bcss.common.redisson.config;

import com.benshou.bcss.common.redisson.RedissonManager;
import com.benshou.bcss.common.redisson.config.props.RedissonRedisProps;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

/**
 * Redis 配置
 *
 * @author <a href="mailto:liuzhenbang@benshou.com">Liu Zhenbang</a>
 */
@Configuration
public class RedissonConfig {

    /**
     * @param redissonRedisProps Redisson 属性
     * @return Redisson 客户端
     */
    @Bean
    public RedissonClient redissonClient(RedissonRedisProps redissonRedisProps) {
        var config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + redissonRedisProps.getHost() + ":" + redissonRedisProps.getPort())
                .setUsername(redissonRedisProps.getUsername())
                .setPassword(Optional.ofNullable(redissonRedisProps.getPassword())
                        .filter(password -> !password.isEmpty())
                        .orElse(null));
        return Redisson.create(config);
    }

    /**
     * @param redissonClient Redisson 客户端
     * @return Redisson 管理器
     */
    @Bean
    public RedissonManager redissonManager(RedissonClient redissonClient) {
        return RedissonManager.builder()
                .redissonClient(redissonClient)
                .build();
    }
}
